import axios from "axios";
import { methods } from "@/mixin";
import whiteList from "@/request/whiteList";
//错误拦截器
export function errorCodeFormat(error, config) {
  if (error) {
    let data = error?.data;
    if (error.response?.data?.code) data = error.response?.data;

    if (typeof this.replaceFilter === "function") {
      this.replaceFilter(data, error);
    } else {
      switch (data?.code) {
        case 401: //令牌失效
          if (axios.defaults.errorTip && config.errorTip !== false) {
            methods
              .$alert({
                type: "danger",
                desc: data?.msg,
              })
          } else {
            //回到小程序
            methods.$toWxBackHome();
          }
          methods.$clearToken();


      }
      if (typeof this.mixinFilter === "function") {
        this.mixinFilter(data, error);
      }
    }
  }
}
//响应拦截器
export function successCodeFormat(response) {
  let a = document.createElement("a");
  a.href = response.config.url;
  //如果有页面内置白名单则替换公共白名单
  let _white = whiteList;
  if (this.whiteList) _white = this.whiteList;
  let defaultOpt =
    response?.data?.code === 200 ||
    _white.find(
      (v) =>
        (v.indexOf && v.indexOf(a.pathname) != -1) ||
        (v.test && v.test(a.pathname))
    );

  if (typeof this.replaceFilter === "function") {
    return this.replaceFilter(response);
  } else {
    if (typeof this.mixinFilter === "function") {
      return this.mixinFilter(response) || defaultOpt;
    } else {
      return defaultOpt;
    }
  }
}

export default function (
  opt = {
    /*
  router
  error/success.replaceFilter 替换现有拦截器 Function(data, error)
  error/success.mixinFilter 在现有拦截器加入规则 Fucntion(data, error)
  whiteList 白名单
  */
  }
) {
  //错误拦截器
  axios.defaults.errorCodeFormat = errorCodeFormat.bind(opt?.error || {});
  axios.defaults.successCodeFormat = successCodeFormat.bind(opt?.success || {});
}
